package Controller;

import Dao.StaffDao;
import Model.Staff;
import Model.StaffChanged;
import Model.User;
import Service.DepartmentService;
import Service.StaffService;
import Service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;
import utils.ReturnDataForLayui;
import utils.ReturnData;
import utils.permission.ConstantsUtils;

@Controller
@RequestMapping("/staff")
public class StaffController {
    private static final Logger logger = LoggerFactory.getLogger(StaffController.class);
    @Autowired
    private StaffService staffService;
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    StaffDao staffDao;
    /**
     * 所有护理人员信息
     * */
    @RequestMapping("/showNursingInfo")
    @ResponseBody
    public PageInfo getNursingInfo (@RequestParam(value="pn",defaultValue = "1",required = true)Integer pn, @RequestParam(value="limit",defaultValue="10",required = true)Integer limit, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String Role_id=this.userService.findRoleIDbyUserNumber(user.getUser_number());
        if(Role_id.equals("2")){
//                  根据user_number找到结算代码（唯一）
            String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
            System.out.println("找到结算代码："+settleCode);
//                  根据结算代码找到护工
            PageHelper.startPage(pn,limit);
            List<Staff> staff=staffService.getStaffbySettleCode(settleCode);
            PageInfo page=new PageInfo(staff);
            return page;
        }else{
            PageHelper.startPage(pn,limit);
            List<Staff> staff=staffService.getAllStaffList();
            PageInfo page=new PageInfo(staff);
            return page;
        }
    }

    /**
     * 所有护理人员变更信息
     * */
    @RequestMapping("/showNursingChangedInfo")
    @ResponseBody
    public PageInfo getNursingChangedInfo (HttpServletRequest request,@RequestParam(value="pn",defaultValue = "1")Integer pn, @RequestParam(value="limit",defaultValue="10")Integer limit){
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String Role_id=this.userService.findRoleIDbyUserNumber(user.getUser_number());
        if(Role_id.equals("2")){
            String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
            System.out.println("找到结算代码："+settleCode);
            PageHelper.startPage(pn,limit);
            List<StaffChanged> nursingChangedInfos=staffService.getStaffChangedsbySettleCode(settleCode);
            PageInfo page=new PageInfo(nursingChangedInfos);
            return page;
        }else{
            PageHelper.startPage(pn,limit);
            List<StaffChanged> nursingChangedInfos=staffService.getAllStaffChangedList();
            PageInfo page=new PageInfo(nursingChangedInfos);
            return page;
        }
    }
    /**
     * 删除护工以及它对应的权限
     */
    @RequestMapping(value = "/delStaff", method = RequestMethod.POST)
    @ResponseBody
    public String delRole(@RequestParam("id") int id) {
        logger.debug("删除护工以及它对应的权限--id-" + id);
        try {
            if (id > 0) {
                return staffService.delStaff(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除护工异常！", e);
        }
        return "删除机构出错，请您稍后再试";
    }

    /**
     * 搜索护工信息详情
     * @param StaffName
     * @param StaffYbid
     * @param StaffSbdw
     * @param StaffZylevel
     * @param StaffStatus
     * @return
     */
    @RequestMapping(value="/searchStaff", method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    @ResponseBody
    public PageInfo findStaffInfo(HttpServletRequest request,@RequestParam(value="pn",defaultValue = "1")Integer pn,
                                  @RequestParam(value="limit",defaultValue="10")Integer limit,
                                  @RequestParam(value="StaffName")String StaffName, @RequestParam(value="StaffYbid")String StaffYbid,
                                  @RequestParam(value="StaffSbdw")String StaffSbdw, @RequestParam(value="StaffZylevel")String StaffZylevel,
                                  @RequestParam(value="StaffStatus")List<String> StaffStatus) {
        System.out.println("StaffStatus:"+StaffStatus);
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String Role_id=this.userService.findRoleIDbyUserNumber(user.getUser_number());

        if (StaffName == "" && StaffYbid=="" && StaffSbdw=="" && StaffZylevel==""&& StaffStatus.size()== 0 ) {
            System.out.println("搜索框无数据");
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                PageHelper.startPage(pn,limit);
                List<Staff> staff=staffService.getStaffbySettleCode(settleCode);
                PageInfo page=new PageInfo(staff);
                return page;
            }else{
                PageHelper.startPage(pn,limit);
                List<Staff> staff = staffService.getAllStaffList();
                System.out.println("limit:"+limit);
                PageInfo page = new PageInfo(staff);
                return page;
            }
        } else {
            System.out.println("contoller层：搜索框非空");
            System.out.println(StaffName+","+StaffYbid+","+StaffSbdw+","+StaffZylevel+","+StaffStatus);
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                PageHelper.startPage(pn,limit);
                List<Staff> staff = staffService.findStaffInfobySettleCode(settleCode,StaffName,StaffYbid,StaffSbdw,StaffZylevel,StaffStatus);
                PageInfo page = new PageInfo(staff);
                return page;
            }else{
                PageHelper.startPage(pn,limit);
                List<Staff> staff = staffService.findStaffInfo(StaffName,StaffYbid,StaffSbdw,StaffZylevel,StaffStatus);
                PageInfo page = new PageInfo(staff);
                return page;
            }
        }
    }

    /**
     * 搜索/变更页面
     * @param nameSearch
     * @param ybidSearch
     * @param titleSearch
     * @return
     */
    @RequestMapping("/searchChangedInfo")
    @ResponseBody
    public PageInfo searchChangedInfo(HttpServletRequest request,@RequestParam(value="pn",defaultValue = "1")Integer pn,
                                      @RequestParam(value="limit",defaultValue="10")Integer limit,
                                      @RequestParam(value = "nameSearch") String nameSearch,
                                      @RequestParam(value="ybidSearch")String ybidSearch,
                                      @RequestParam(value="titleSearch")String titleSearch) {
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String Role_id=this.userService.findRoleIDbyUserNumber(user.getUser_number());
        if (nameSearch == "" && ybidSearch =="" && titleSearch =="") {
            System.out.println("搜索框无数据");
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                PageHelper.startPage(pn,limit);
                List<StaffChanged> staffChangeds=staffService.getStaffChangedsbySettleCode(settleCode);
                PageInfo page=new PageInfo(staffChangeds);
                return page;
            }else{
                PageHelper.startPage(pn,limit);
                List<StaffChanged> staffChangeds = staffService.getAllStaffChangedList();
                PageInfo page = new PageInfo(staffChangeds);
                return page;
            }
        }
        else{
            System.out.println("contoller层：搜索框非空");
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                PageHelper.startPage(pn,limit);
                List<StaffChanged> changedInfo = staffService.findStaffChangedInfobySettleCode(nameSearch,ybidSearch,titleSearch,settleCode);
                PageInfo page = new PageInfo(changedInfo);
                return page;
            }else{
                PageHelper.startPage(pn,limit);
                List<StaffChanged> changedInfo = staffService.findStaffChangedInfo(nameSearch,ybidSearch,titleSearch);
                PageInfo page = new PageInfo(changedInfo);
                return page;
            }
        }
    }

    /**
     * 更新护工数据
     */
    @RequestMapping(value = "/updateStaff", method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    @ResponseBody
    public String updateNursing(Staff staff, HttpSession session,HttpServletRequest request) {
        try {
            User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
            String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
            System.out.println("开始更新");
            System.out.println("启变日期："+staff.getStart_change_date());
            String abc=staffService.updateNursing(staff,settleCode,session);
            System.out.println("返回结果："+abc);
            if(abc=="ok"){
                return "{\"msg\":\"ok\"}";
            }else{
                return "{\"msg\":\"error\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新异常！", e);
            return "操作异常，请您稍后再试";
        }
    }

    /**
     * 创建护工数据
     */
    @RequestMapping(value = "/AddStaff")
    @ResponseBody
    public String AddNursing(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        System.out.println("欢迎添加护工");
        System.out.println("[ Service: Add News Information ]");
        int StaUpdate = 0;
        Staff staff= new Staff();
        staff.setYbid(request.getParameter("ybid"));
        staff.setName(request.getParameter("name"));
        //System.out.println(staff.getName());
        staff.setGender(request.getParameter("gender"));
        staff.setId_number(request.getParameter("id_number"));
        staff.setPhone_number(request.getParameter("phone_number"));
        staff.setZylevel(request.getParameter("zylevel"));
        staff.setWorklength(request.getParameter("worklength"));
        staff.setStatus(request.getParameter("status"));
        //System.out.println("getStatue"+staff.getStatus());
        staff.setRylb(request.getParameter("rylb"));
        staff.setServ_org(request.getParameter("serv_org"));
        staff.setLastserv_org(request.getParameter("lastserv_org"));
        staff.setSbdw(request.getParameter("sbdw"));
        staff.setSbdwcode(request.getParameter("sbdwcode"));
        staff.setCertificate_code(request.getParameter("certificate_code"));
        System.out.println("查询护工状态"+staff.getYbid());
        try {
            Staff StfStatus=staffDao.getStaffStatus(staff.getYbid());
            System.out.println("查询该护工状态："+StfStatus.getStatus());
            if(StfStatus.getStatus().equals("无效转出")){
                System.out.println("更新护工：");
                StaUpdate=staffDao.updateStaffStatus(staff);
                System.out.println("更新护工：");
                return "{\"msg\":\"ok\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("更新状况："+StaUpdate);
        if( StaUpdate==1){
            System.out.println("更新成功");
            return "{\"msg\":\"ok\"}";
        }
        //System.out.println("111111");


        try {
            staffDao.createStaff(staff);
            System.out.println("getStatue1"+staff.getStatus());
            System.out.println(staff.getName());
            return "{\"msg\":\"ok\"}";
            //status = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{\"msg\":\"error\"}";

    }


    /**
     * 上传Excel获取护工数据
     */
    @RequestMapping(value = "/InputExcel")
    @ResponseBody
    public String InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        String flag = "02";// 上传标志
        System.out.println("controller层：进入上传接口");
        if (!file.isEmpty()) {
            try {
                User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());

                String originalFilename = file.getOriginalFilename();// 原文件名字
                System.out.println("文件名：" + originalFilename);
                InputStream is = file.getInputStream();// 获取输入流
                flag = staffService.InputExcel(is, originalFilename,settleCode);
                System.out.println("controller层：上传成功，flag= "+flag);
                return "{\"msg\":\"ok\"}";
            } catch (Exception e) {
                flag = "03";// 上传出错
                e.printStackTrace();
                System.out.println("controller层：上传失败，flag= "+flag);
            }
        }
        return "{\"msg\":\"error\"}";
    }

    @RequestMapping("/getList")
    @ResponseBody
    public ReturnDataForLayui getList(Staff staff){
        return staffService.getList(staff);
    }

    @RequestMapping("/getList2")
    @ResponseBody
    public ReturnDataForLayui getList2(Staff staff){
        return staffService.getList2(staff);
    }
    @RequestMapping("/updatePhone")
    @ResponseBody
    public ReturnData updatePhone(Staff staff){

        return staffService.updatePhone(staff);
    }
    /**
     * 信息页面/Excel导出护工数据
     * @param StaffName
     * @param StaffYbid
     * @param StaffSbdw
     * @param StaffZylevel
     * @param StaffStatus
     * @return
     */
    @RequestMapping(value="/ExportAllInfo",method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    @ResponseBody
    public List<Staff> StaffInfo(HttpServletRequest request,@RequestParam(value="StaffName")String StaffName,@RequestParam(value="StaffYbid")String StaffYbid,
                                 @RequestParam(value="StaffSbdw")String StaffSbdw,@RequestParam(value="StaffZylevel")String StaffZylevel,
                                 @RequestParam(value="StaffStatus")List<String> StaffStatus){
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String Role_id=this.userService.findRoleIDbyUserNumber(user.getUser_number());
        if (StaffName == "" && StaffYbid=="" && StaffSbdw=="" && StaffZylevel==""&& StaffStatus.size()== 0 ) {
            System.out.println("搜索框无数据");
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                List<Staff> staff=staffService.getStaffbySettleCode(settleCode);
                return staff;
            }else{
                List<Staff> staff = staffService.getAllStaffList();
                return staff;
            }
        } else {
            System.out.println("contoller层：搜索框非空");
            System.out.println(StaffName+","+StaffYbid+","+StaffSbdw+","+StaffZylevel+","+StaffStatus);
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                List<Staff> staff = staffService.findStaffInfobySettleCode(settleCode,StaffName,StaffYbid,StaffSbdw,StaffZylevel,StaffStatus);
                return staff;
            }else{
                List<Staff> staff = staffService.findStaffInfo(StaffName,StaffYbid,StaffSbdw,StaffZylevel,StaffStatus);
                return staff;
            }
        }
    }

    /**
     * 导出Excel/变更页面
     * @param nameSearch
     * @param ybidSearch
     * @param titleSearch
     * @return
     */
    @RequestMapping("/ExportAllChangedInfo")
    @ResponseBody
    public List<StaffChanged> ExportAllChangedInfo(HttpServletRequest request,@RequestParam(value = "nameSearch") String nameSearch,
                                      @RequestParam(value="ybidSearch")String ybidSearch,
                                      @RequestParam(value="titleSearch")String titleSearch) {
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String Role_id=this.userService.findRoleIDbyUserNumber(user.getUser_number());
        if (nameSearch == "" && ybidSearch =="" && titleSearch =="") {
            System.out.println("搜索框无数据");
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                List<StaffChanged> staffChangeds=staffService.getStaffChangedsbySettleCode(settleCode);
                return staffChangeds;
            }else{
                List<StaffChanged> staffChangeds = staffService.getAllStaffChangedList();
                return staffChangeds;
            }
        }
        else{
            System.out.println("contoller层：搜索框非空");
            if(Role_id.equals("2")){
                String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
                List<StaffChanged> changedInfo = staffService.findStaffChangedInfobySettleCode(nameSearch,ybidSearch,titleSearch,settleCode);
                return changedInfo;
            }else{
                List<StaffChanged> changedInfo = staffService.findStaffChangedInfo(nameSearch,ybidSearch,titleSearch);
                return changedInfo;
            }
        }
    }

    /**
     * 制定派工日程页面：查找是否存在该护工
     * @param StaffYbid
     * @return
     */
    @RequestMapping("/searchStaffbyYbid")
    @ResponseBody
    public String searchStaffbyYbid(@RequestParam(value = "StaffYbid") String StaffYbid) {
        System.out.println("controller层/根据医保ID找护工："+StaffYbid);
        List<Staff> findout = staffService.searchStaffbyYbid(StaffYbid);
        System.out.println("controller层：搜索成功");
        if(findout==null){
            return "noStaff";
        }else{
            return "existStaff";
        }
    }

    /**
     * 微信小程序：注册：查找是否存在该护工，并插入密码
     * @param StaffID
     * @param StaffYbid
     * @param StaffPassword
     * @return
     */
    @RequestMapping("/wechatRegisterStaff")
    @ResponseBody
    public String wechatRegisterStaff(@RequestParam(value = "StaffID") String StaffID,
                                    @RequestParam(value = "StaffYbid") String StaffYbid,
                                    @RequestParam(value="StaffPassword")String StaffPassword) {
        try{
            System.out.println("controller层：护工ID："+StaffID);
            System.out.println("controller层：护工医保ID："+StaffYbid);
            System.out.println("controller层：护工密码："+StaffPassword);
            String register=staffService.wechatRegisterStaff(StaffID,StaffYbid,StaffPassword);
            switch (register){
                case "SuccessRegister":return "SuccessRegister";
                case "AlreadyExist":return "AlreadyExist";
                case "Incompatible":return "Incompatible";
                case "errorYbid":return "errorYbid";
            }
            System.out.println("controller层：搜索成功");
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("护工注册异常！", e);
        }
        return "error";
    }

    /**
     * 微信小程序：个人主页：查找登录护工，返回个人信息
     * @param StaffYbid
     * @return
     */
    @RequestMapping("/wechatSearchStaffbyYbid")
    @ResponseBody
    public List<Staff> wechatSearchStaffbyYbid(@RequestParam(value = "StaffYbid") String StaffYbid) {
        System.out.println("controller层/根据医保ID找护工："+StaffYbid);
        List<Staff> staff = staffService.searchStaffbyYbid(StaffYbid);
        System.out.println("controller层：搜索成功");
        return staff;
    }

//    /**
//     * 制定派工日程页面：查找是否存在该护工
//     * @param StaffYbid
//     * @return
//     */
//    @RequestMapping("/searchStaffbyYbid")
//    @ResponseBody
//    public String searchChangedInfo(@RequestParam(value = "StaffYbid") String StaffYbid) {
//        System.out.println("controller层/根据医保ID找护工："+StaffYbid);
//        List<Staff> findout = staffService.searchStaffbyYbid(StaffYbid);
//        System.out.println("controller层：搜索成功");
//        if(findout==null){
//            return "noStaff";
//        }else{
//            return "existStaff";
//        }
//    }

    @RequestMapping("/getHgIdName")
    @ResponseBody
    public List<Staff> getHgIdName(){
        List<Staff> list = staffService.getHgIdName();
        System.out.println("controller层：获取护工ID和name成功");
        return list;
    }

    /**
     * 根据机构查找护工姓名
     * @return
     */
    @RequestMapping("/getHgNameByCode")
    @ResponseBody
    public List<Staff> getHgNameByCode(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
        System.out.println("找到结算代码："+settleCode);
        List<Staff> list = staffService.getHgNameByCode(settleCode);
        System.out.println("controller层：获取护工姓名成功！");
        return list;
    }

    /**
     * 根据护工姓名查找身份证号
     * @return
     */
    @RequestMapping("/getHgIdNumberByName")
    @ResponseBody
    public List<Staff> getHgIdNumberByName(HttpServletRequest request){
        String name = request.getParameter("hg_name");
        System.out.println("护工的姓名："+name);
        List<Staff> list = staffService.getHgIdNumberByName(name);
        System.out.println("controller层：获取护工身份证成功！");
        return list;
    }

    @RequestMapping("/updateHgDevice")
    @ResponseBody
    public int updateHgDevice(HttpServletRequest request,Staff staff){
        staff.setId_number(request.getParameter("hg_id_number"));
        int status = 0;
        try {
            staffService.updateHgDevice(staff);
            System.out.println("更新护工的设备（发放后添加）！");
        }catch (Exception e){
            status = -1;
            e.printStackTrace();
        }
        return status;
    }


    @RequestMapping("/getDeviceByOpenId")
    @ResponseBody
    public List<Staff> getDeviceByOpenId(HttpServletRequest request,Staff staff){
        System.out.println("[Controller层:根据open_id获取设备！]");
        List<Staff> list = staffService.getDeviceByOpenId(staff);
        return list;
    }
}
